const express = require('express');
const { Op } = require('sequelize');
const router = express.Router();
const { Course, Category, User, Chapter } = require('../../models');
const { success, failure } = require('../../utils/responses');
const { NotFound, Conflict } = require('http-errors');
/**
 * 公共方法：白名单过滤
 * @param req
 * @returns {{image: *, name, introductory: (boolean|*), userId: (number|*), categoryId: (number|*), content, recommended: (boolean|*)}}
 */
const filterBody = (req) => {
  return {
    categoryId: req.body.categoryId,
    name: req.body.name,
    image: req.body.image,
    recommended: req.body.recommended,
    introductory: req.body.introductory,
    content: req.body.content,
    free: req.body.free,
  };
};

/**
 * 公共方法：关联分类、用户数据
 * @returns {{include: [{as: string, model, attributes: string[]}], attributes: {exclude: string[]}}}
 */
const getCondition = () => {
  return {
    attributes: { exclude: ['CategoryId', 'UserId'] },
    include: [
      {
        model: Category,
        as: 'category',
        attributes: ['id', 'name'],
      },
      {
        model: User,
        as: 'user',
        attributes: ['id', 'username', 'avatar'],
      },
    ],
  };
};

/**
 * 公共方法：查询当前课程
 */
const getCourse = async (req) => {
  // 获取课程 ID
  const { id } = req.params;
  const condition = getCondition();
  // 查询当前课程
  const course = await Course.findByPk(id, condition);

  // 如果没有找到，就抛出异常
  if (!course) {
    throw new NotFound(`ID: ${id}的课程未找到`);
  }

  return course;
};

/**
 * 查询课程列表
 * GET /admin/courses
 */
router.get('/', async (req, res) => {
  try {
    const query = req.query;

    // 当前是第几页，如果不传，那就是第一页
    const currentPage = Math.abs(Number(query.current)) || 1;
    // 每页显示多少条数据，如果不传，那就显示10条
    const pageSize = Math.abs(Number(query.pageSize)) || 10;
    // 计算 offset
    const offset = (currentPage - 1) * pageSize;

    const condition = {
      ...getCondition(),
      order: [['id', 'DESC']],
      limit: pageSize,
      offset,
      where: {},
    };
    if (query.categoryId) {
      condition.where.categoryId = query.categoryId;
    }

    if (query.userId) {
      condition.where.userId = query.userId;
    }

    if (query.name) {
      condition.where.name = {
        [Op.like]: `%${query.name}%`,
      };
    }

    if (query.recommended) {
      condition.where.recommended = query.recommended === 'true';
    }

    if (query.introductory) {
      condition.where.introductory = query.introductory === 'true';
    }

    // 查询数据
    const { count, rows } = await Course.findAndCountAll(condition);

    success(res, '查询课程列表成功', {
      data: rows,
      total: count,
    });
  } catch (error) {
    failure(res, error);
  }
});
/**
 * 查询课程详情
 * GET /admin/courses/:id
 */
router.get('/:id', async (req, res) => {
  try {
    // 查询数据
    const course = await getCourse(req);
    success(res, '查询课程详情成功', { data: course });
  } catch (error) {
    failure(res, error);
  }
});
/**
 * 创建课程
 * GPOST /admin/courses/add
 */
router.post('/add', async (req, res) => {
  try {
    // 创建课程
    const body = filterBody(req);
    body.userId = req.user.id;
    const course = await Course.create(body);
    success(res, '创建课程成功', { data: course }, 201);
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 删除课程
 * DELETE /admin/courses/:id
 */
router.delete('/:id', async (req, res) => {
  try {
    const course = await getCourse(req);

    const count = await Chapter.count({ where: { courseId: req.params.id } });
    if (count > 0) {
      throw new Conflict('当前课程有章节，无法删除。');
    }
    // 删除课程
    await course.destroy();
    success(res, '删除课程成功');
  } catch (error) {
    failure(res, error);
  }
});
/**
 * 更新课程
 * PUT /admin/courses/:id
 */
router.put('/:id', async (req, res) => {
  try {
    const course = await getCourse(req);
    // 更新课程
    const body = filterBody(req);
    body.userId = req.user.id;
    const updateCourse = await course.update(body);
    success(res, '更新课程成功', { data: updateCourse });
  } catch (error) {
    failure(res, error);
  }
});

module.exports = router;
